package com.cnblsp2.android.study.dbandio.sharedprefer;

import java.text.SimpleDateFormat;
import java.util.Date;

import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

import com.cnblsp2.android.study.dbandio.R;

public class SharedPreferencesActivity extends Activity {

	SharedPreferences sharedPreferences = null;
	SharedPreferences.Editor editor = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		this.setContentView(R.layout.activity_sharedpreferences);
		// 获取只能被本应用程序读、写的SharedPreferences 对象
		sharedPreferences = getSharedPreferences("cnblsp2", MODE_PRIVATE);
		editor = sharedPreferences.edit();
		Button readBtn = (Button) this.findViewById(R.id.activity_sharedpreferences_read_btn);
		Button writeBtn = (Button) this.findViewById(R.id.activity_sharedpreferences_write_btn);
		readBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// 读取字符串数据
				String time = sharedPreferences.getString("time", null);
				// 读取int类型数据
				int randNum = sharedPreferences.getInt("random", 0);
				String result = time == null ? "你暂时未写入数据" : "写入时间为:" + time + "\n上次生成随机数为:" + randNum;
				//
				Toast.makeText(SharedPreferencesActivity.this, result, 5000).show();
			}
		});
		writeBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 " + "hh:mm:ss");
				// 存入当前时间
				editor.putString("time", sdf.format(new Date()));
				// 存入一个随机数
				editor.putInt("random", (int) (Math.random() * 100));
				// 提交所有存入的数据
				editor.commit();
			}
		});

	}

}
